home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1721 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  67 lines

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: swap high and low 16 bits?
  5. Date: 16 Jan 1996 16:00:16 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan16110016@g7240065.bridge.bst.bls.com>
  8. References: <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: Bill Simpson's message of Mon, 15 Jan 1996 17:55:15 -0600
  11.  
  12. In article <Pine.OSF.3.91.960115174921.19742A-100000@io.UWinnipeg.ca> Bill Simpson <wsimpson@uwinnipeg.ca> writes:
  13.  
  14. :   I wanted to obtain a "random" starting number each time a program
  15. :   is run.  The obvious choice is time(NULL).  The problem with it is that
  16. :   if the program runs and terminates fairly quickly, the number returned by 
  17. :   time(NULL) is quite similar each run, differing only by the lowest bits.
  18.  
  19. :   One solution would be to swap the high 16 bits and the low 16 bits of the
  20. :   32 bit unsigned long int.  Sorry this is dirty, not ANSI.
  21.  
  22. :   Could anyone please tell me how to do this?  The simpler the code the
  23. :   better (ANSI not important for this particular case).
  24.  
  25. :   Other solutions to the general problem (e.g. rotating the low bits to
  26. :   the high end) are welcome.
  27.  
  28. The way I understand you is that you are using the result of time() as your
  29. random number.
  30. The standard C library has a rand() function which can be seeded by
  31. the time() function with a call to srand(). A word of warning is that
  32. many of these rand() functions are notorious bad in the low order bits.
  33.  
  34. Example for some range 0 to N-1:
  35.     ...
  36.     srand(time(0));
  37.     ...
  38.     rand() / (RAND_MAX / N + 1)
  39.     ...
  40.  
  41. See FAQ 13.16 and 13.17
  42.  
  43. If you really want to swap the low 16 bits with the high 16 bits try:
  44. NB: Assumes 32 bit long's
  45.  
  46.     unsigned long a;
  47.     a = (unsigned long)time(0);
  48.     a = (a << 16) | (a >> 16);
  49.  
  50. or more ANSI like - shift the low half bits with high half bits.
  51.  
  52. #include <limits.h>
  53.  
  54.     unsigned long a;
  55.     int shift = CHAR_BIT * sizeof(unsigned long) / 2
  56.  
  57.     a = (unsigned long)time(0);
  58.     a = (a << shift) | (a >> shift);
  59.  
  60. Hope this helps
  61. Regards
  62.  
  63.    -A.
  64.  
  65. -- 
  66. | A.Champion                |
  67.